package chances.epg.commons.utils;

/**
 * 
 */

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

/**
 * @author zz
 * 
 */
public class MD5Utils {

    private static final int BUFFER_SIZE = 1024 * 10;

    /**
     * 将字节数组转换为16进制字符串.
     * 
     * @param data
     *            进行转换的字节数组
     * @return 16进制的字符串
     */
    public static String byte2HexString(byte[] data) {
        StringBuffer checksumSb = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            String hexStr = Integer.toHexString(0x00ff & data[i]);
            if (hexStr.length() < 2) {
                checksumSb.append("0");
            }
            checksumSb.append(hexStr);
        }
        return checksumSb.toString();
    }

    /**
     * 生成MD5摘要.
     * 
     * @param str
     *            生进行摘要的内容
     * @return 返回摘要16进制串
     */
    public static String MD5(File file) {
        if (file == null) {
            return null;
        }
        FileInputStream in = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);

            final byte[] buffer = new byte[BUFFER_SIZE];
            while (true) {
                final int nread = in.read(buffer);
                if (nread < 0) {
                    break;
                }
                messageDigest.update(buffer, 0, nread);
            }
            return byte2HexString(messageDigest.digest());
        } catch (Exception e) {
            throw new SecurityException(e.getMessage());
        } finally {
            closeIO(in);
        }
    }

    /**
     * @param in
     */
    private static void closeIO(FileInputStream in) {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
    }
}
